package com.fc.employee.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fc.commonutils.JwtUtils;
import com.fc.commonutils.MD5;
import com.fc.employee.entity.Employee;
import com.fc.employee.mapper.EmployeeMapper;
import com.fc.employee.service.EmployeeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fc.servicebase.exceptionhandler.FcException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zwy
 * @since 2022-09-05
 */
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public String login(String phone, String password) {

        //手机号和密码非空判断
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(password)) {
            throw new FcException(20001, "手机号和密码不能为空");
        }
        password = MD5.encrypt(password);
        //通过手机号查找employee
        QueryWrapper<Employee> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone);
        Employee employeeByPhone = employeeMapper.selectOne(queryWrapper);

        //如果没有查到
        if (employeeByPhone == null) {
            throw new FcException(20001, "手机号不存在");
        }

        //判断密码
        if (!password.equals(employeeByPhone.getPassword())) {
            throw new FcException(20001, "密码不正确");
        }

        return JwtUtils.getJwtToken(employeeByPhone.getId().toString(), employeeByPhone.getName());
    }
}
